import React, { Component } from 'react';
import { connect } from 'dva';
import { Link } from 'dva/router';
import {
    notification,
    Modal,
    Form,
    Input,
    Button,
    Checkbox,
    Row,
    Col,
    Popover,
    Progress,
} from 'antd';
import styles from './Register.less';
import Security from './Security';
import { seccode } from '../../services/session-auth';

const FormItem = Form.Item;

const passwordStatusMap = {
    ok: <div className={styles.success}>强度：强</div>,
    pass: <div className={styles.warning}>强度：中</div>,
    poor: <div className={styles.error}>强度：太短</div>,
};

const passwordProgressMap = {
    ok: 'success',
    pass: 'normal',
    poor: 'exception',
};

@connect(({ register, loading }) => ({
    register,
    submitting: loading.effects['register/submit'],
})) //eslint-disable-line
@Form.create()
export default class Register extends Component {
    state = {
        count: 0,
        confirmDirty: false,
        visible: false,
        help: '',
        loading: false,
        loadingSignUp: false,
    };

    componentWillUnmount() {
        clearInterval(this.interval);
    }

    onGetCaptcha = () => {
        const { form } = this.props;
        form.validateFields(['mobile'], err => {
            if (err && typeof err.mobile !== 'undefined') {
                return false;
            }
            const mobile = form.getFieldValue('mobile');
            this.setState({
                loading: true,
            });
            // 这里得用promise
            seccode({ phone: mobile })
                .then(() => {
                    notification.success({
                        message: '短信验证码发送成功',
                        description: '',
                    });
                })
                .catch(e => {
                    const { message } = e;
                    notification.error({
                        message: '获取验证码失败',
                        description: message,
                    });
                    throw e;
                })
                .then((ttl = 60) => {
                    this.setState({
                        loading: false,
                    });
                    let count = ttl;
                    this.setState({ count });
                    this.interval = setInterval(() => {
                        count -= 1;
                        this.setState({ count });
                        if (count === 0) {
                            clearInterval(this.interval);
                        }
                    }, 1000);
                })
                .catch(e => {
                    this.setState({
                        loading: false,
                    });
                    this.restCaptcha();
                });
        });
    };
    restCaptcha = () => {
        if (this.interval) {
            clearInterval(this.interval);
        }
        this.setState({ count: 0 });
    };
    getPasswordStatus = () => {
        const { form } = this.props;
        const value = form.getFieldValue('password');
        if (value && value.length > 9) {
            return 'ok';
        }
        if (value && value.length > 5) {
            return 'pass';
        }
        return 'poor';
    };

    handleSubmit = e => {
        e.preventDefault();
        const { form, dispatch } = this.props;
        const that = this;
        form.validateFields({ force: true }, (err, values) => {
            that.restCaptcha();
            this.setState({
                visible: false,
            });
            const { mobile: account, password, captcha: seccode } = values;
            if (!err) {
                dispatch({
                    type: 'register/submit',
                    payload: {
                        account,
                        password,
                        seccode,
                    },
                });
            }
        });
    };
    handleSecurityClick() {
        Modal.info({
            title: '安全协议',
            content: <Security />,
            width: 800,
        });
    }
    handleConfirmBlur = e => {
        const { value } = e.target;
        const { confirmDirty } = this.state;
        this.setState({ confirmDirty: confirmDirty || !!value });
    };
    onBlurHandle() {
        this.setState({
            visible: false,
        });
    }
    checkSecurity = (rule, value, callback) => {
        if (!value) {
            callback('请确定是否同意安全协议');
        } else {
            callback();
        }
    };
    checkConfirm = (rule, value, callback) => {
        const { form } = this.props;
        if (value && value !== form.getFieldValue('password')) {
            callback('两次输入的密码不匹配!');
        } else {
            callback();
        }
    };
    checkPassword = (rule, value, callback) => {
        if (!value) {
            this.setState({
                help: '请输入密码！',
                visible: !!value,
            });
            callback('error');
        } else {
            this.setState({
                help: '',
            });
            const { visible, confirmDirty } = this.state;
            if (!visible) {
                this.setState({
                    visible: !!value,
                });
            }
            if (value.length < 6) {
                callback('error');
            } else {
                const { form } = this.props;
                if (value && confirmDirty) {
                    form.validateFields(['confirm'], { force: true });
                }
                callback();
            }
        }
    };

    changePrefix = value => {
        this.setState({
            prefix: value,
        });
    };

    renderPasswordProgress = () => {
        const { form } = this.props;
        const value = form.getFieldValue('password');
        const passwordStatus = this.getPasswordStatus();
        return value && value.length ? (
            <div className={styles[`progress-${passwordStatus}`]}>
                <Progress
                    status={passwordProgressMap[passwordStatus]}
                    className={styles.progress}
                    strokeWidth={6}
                    percent={value.length * 10 > 100 ? 100 : value.length * 10}
                    showInfo={false}
                />
            </div>
        ) : null;
    };

    render() {
        const { form, submitting } = this.props;
        const { getFieldDecorator } = form;
        const { count, help, visible, loading } = this.state;
        return (
            <div className={styles.main}>
                <div className={styles.introduce} />
                <div className={styles.login}>
                    <Form onSubmit={this.handleSubmit} className={styles.input}>
                        <FormItem>
                            {getFieldDecorator('mobile', {
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入手机号！',
                                    },
                                    {
                                        pattern: /^1\d{10}$/,
                                        message: '手机号格式错误！',
                                    },
                                ],
                            })(<Input size="large" placeholder="11位手机号" />)}
                        </FormItem>
                        <FormItem>
                            <Row gutter={8}>
                                <Col span={14}>
                                    {getFieldDecorator('captcha', {
                                        rules: [
                                            {
                                                required: true,
                                                message: '请输入验证码！',
                                            },
                                        ],
                                    })(<Input size="large" placeholder="验证码" />)}
                                </Col>
                                <Col span={10}>
                                    <Button
                                        size="large"
                                        disabled={count}
                                        className={styles.getCaptcha}
                                        onClick={this.onGetCaptcha}
                                        loading={loading}
                                    >
                                        {count ? `${count} s` : '获取验证码'}
                                    </Button>
                                </Col>
                            </Row>
                        </FormItem>
                        <FormItem help={help}>
                            <Popover
                                content={
                                    <div style={{ padding: '4px 0' }}>
                                        {passwordStatusMap[this.getPasswordStatus()]}
                                        {this.renderPasswordProgress()}
                                        <div style={{ marginTop: 10 }}>
                                            请至少输入 6 个字符。请不要使用容易被猜到的密码。
                                        </div>
                                    </div>
                                }
                                overlayStyle={{ width: 240 }}
                                placement="right"
                                visible={visible}
                            >
                                {getFieldDecorator('password', {
                                    rules: [
                                        {
                                            validator: this.checkPassword,
                                        },
                                    ],
                                })(
                                    <Input
                                        // fix 提示框弹出不收回体验
                                        onBlur={this.onBlurHandle.bind(this)}
                                        size="large"
                                        type="password"
                                        placeholder="至少6位密码，区分大小写"
                                    />
                                )}
                            </Popover>
                        </FormItem>
                        <FormItem>
                            {getFieldDecorator('confirm', {
                                rules: [
                                    {
                                        required: true,
                                        message: '请确认密码！',
                                    },
                                    {
                                        validator: this.checkConfirm,
                                    },
                                ],
                            })(<Input size="large" type="password" placeholder="确认密码" />)}
                        </FormItem>
                        <FormItem>
                            {getFieldDecorator('security', {
                                valuePropName: 'checked',
                                initialValue: false,
                                rules: [
                                    {
                                        required: true,
                                        message: '请确认是否同意安全协议！',
                                    },
                                    {
                                        validator: this.checkSecurity,
                                    },
                                ],
                            })(<Checkbox />)}
                            <a
                                className={styles.security}
                                onClick={this.handleSecurityClick.bind(this)}
                            >
                                平台安全协议
                            </a>
                        </FormItem>
                        <FormItem>
                            <Button
                                size="large"
                                loading={submitting}
                                className={styles.submit}
                                type="primary"
                                htmlType="submit"
                            >
                                注册
                            </Button>
                        </FormItem>
                        <div className={styles.loginLg}>
                            已有账户？立即
                            <Link
                                className={styles.loginLg}
                                style={{ color: ' #2A76D1' }}
                                to="/user/login"
                            >
                                登录
                            </Link>
                        </div>
                    </Form>
                </div>
            </div>
        );
    }
}
